﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Jabr.Logic.Roster;

namespace Jabr.GUI.Forms
{
    public partial class AccountJabberEdit : AccountGenericEdit
    {
        public AccountJabberEdit(AbstractAccount acc)
        {
            InitializeComponent();

            this.JabberAccountBindingSource.DataSource = (JabberAccount)acc;
            if (acc.New)
                this.OkBtn.Text = "Register";
        }

        private void OkBtn_Click(object sender, EventArgs e)
        {
            var ja = (JabberAccount)this.JabberAccountBindingSource.Current;
            if (ja.New)
            {
                this.Enabled = false;
                ja.OnRegister += delegate(LoginResultType res, object oe)
                {
                    if (res == LoginResultType.SUCCESS)
                    {
                        ja.New = false;
                        ja.Disconnect();
                    }
                    else
                    {
                        MessageBox.Show("Account creation failed. Maybe try a diffrent JabberID.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    if (this.InvokeRequired)
                        this.Invoke(new invoke_Result_delegate(invoke_Result), new object[] { res });
                    else
                        this.invoke_Result(res);
                };
                ja.Connect();
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private delegate void invoke_Result_delegate(LoginResultType res);
        private void invoke_Result(LoginResultType res)
        {
            if (res == LoginResultType.SUCCESS)
                this.OkBtn.Text = "OK";
            this.Enabled = true;
        }
    }
}
